<?php
/**
 * Created by PhpStorm.
 * User: dayu
 * Date: 2019/12/24
 * Time: 14:45
 */

namespace app\api\controller;


use data\model\CityModel;
use data\model\DistrictModel;
use data\model\NsShopModel;
use data\model\ProvinceModel;
use think\Controller;
use app\Validate\LoginValidate;
use data\model\UserModel;
use data\model\NsMemberAccountModel;
use data\service\SecretToken;
use data\service\WXBizDataCrypt;
use think\cache\driver\Redis;
use think\Request;
use think\Db;

class Login extends BaseController
{


    /**
     * 登录
     * @param LoginValidate $loginValidate
     * @return string
     * @throws \Exception
     */
    public function index(LoginValidate $loginValidate)
    {
        $db = new UserModel;
        $shopInfo = new NsShopModel();
        $member = new NsMemberAccountModel();

        $account = $loginValidate->request->post('account');
        $password = $loginValidate->request->post('password');
        $code = $loginValidate->request->post('code');
        $uid = $db->where(['is_system' => 0, "is_member" => 1, "user_status" => 1, "user_tel" => $account, "user_password" => md5($password)])->value('uid');
        if (empty($uid)) {
            return return_json_data('登录失败1', 500);
        }
        $shop_id = $member->where('uid', $uid)->value('shop_id');
        $shop_name = $shopInfo->where('shop_id', $shop_id)->value('shop_name');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . config('wxConfig')['APPID'] . "&secret=" . config('wxConfig')['APPSECRET'] . "&js_code=" . $code . "&grant_type=authorization_code";
        $res = json_decode(file_get_contents($url), true);
        if (isset($res['errcode'])) return return_json_data($res['errmsg'], 500);

        $userData = [
            'user_id' => $uid,
            'shop_name' => $shop_name,
            'openid' => $res['openid'],
            'shop_id' => $shop_id,
            'session_key' => $res['session_key'],
        ];
        $boole = (new SecretToken())->disposeToken($userData);

        if ($boole === false) {
            return return_json_data('登录失败2', 500);
        }
        return return_json_data(["code" => getNonceStr(10) . base64_encode(json_encode($boole))], 200);
    }

    //刷新令牌
    public function disposeToken()
    {
        $secret = request()->post('secret', '');
        if (empty($secret)) {
            return return_json_data(AjaxReturn(PARAMS_DEFICIENCY, '', true), 604);
        }
        $db = new SecretToken();
        $data = $db->disposeToken($secret, true);
        if ($data === false) {
            return return_json_data(AjaxReturn(TOKEN_CREATE_ERROR, '', true), 602);
        } else {
            return return_json_data(["code" => getNonceStr(10) . base64_encode(json_encode($data))], 200);
        }
    }


    public function openId()
    {
        $code = request()->post('code');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . config('wxPay')['APPID'] . "&secret=" . config('wxPay')['SECRET'] . "&js_code=" . $code . "&grant_type=authorization_code";
        $res = json_decode(http($url), true);
        if (isset($res['errcode'])) return return_json_data($res['errmsg'], 500);
        return return_json_data($res, 200);

    }

    /**
     * 手机号获取
     * @param LoginValidate $loginValidate
     * @return string
     * @throws \Exception
     */
    public function decodePhone(LoginValidate $loginValidate)
    {
        $data = [];
        $sessionKey = request()->post('sessionKey');
        $encryptedData = request()->post('encryptedData');
        $iv = request()->post('iv');
        $boole = (new WXBizDataCrypt())->decryptData($sessionKey, $encryptedData, $iv, $data);
        if($boole==0){
            return return_json_data(json_decode($data,true), 200);
        }
        return return_json_data($boole, 500);
    }


    public function address()
    {
//        $p = new ProvinceModel();
//        $c = new CityModel();
//        $d = new DistrictModel();
        $_p = '[';
        $_p_data = Db::table('sys_province')->field('province_id,province_name')->select();
//        $c = Db::table('sys_city')->where('status', 1)->select();
//        $d = Db::table('sys_district')->where('status', 1)->select();
        foreach ($_p_data as $k => $v) {
            $_p .=PHP_EOL.'{"label": "'.$v['province_name'].'","value": "'.$v['province_id'].'"}'.PHP_EOL;
        }


        var_dump($_p.']');

        $_a = '[{"label": "北京市","value": "11"}]';


    }

}